package cn.chengpengper.rpc.proxy.javassist;

import cn.chengpengper.rpc.proxy.api.BaseProxyFactory;
import cn.chengpengper.rpc.proxy.api.ProxyFactory;
import cn.chengpengper.rpc.spi.annotation.SpiClass;
import javassist.util.proxy.Proxy;
import lombok.extern.slf4j.Slf4j;

/**
 * @author chengpeng.hu
 */
@Slf4j
@SpiClass
public class JavassistProxyFactory<T> extends BaseProxyFactory<T> implements ProxyFactory {
    private javassist.util.proxy.ProxyFactory proxyFactory = new javassist.util.proxy.ProxyFactory();

    @Override
    public <T> T getProxy(Class<T> clazz) {
        try {
            log.info("基于Javassist动态代理...");
            //设置代理类的父类
            proxyFactory.setInterfaces(new Class[]{clazz});
            // 通过字节码技术动态创建子类实例
            Proxy proxy = (Proxy) proxyFactory.createClass().newInstance();
            proxy.setHandler((self, thisMethod, proceed, args) -> objectProxy.invoke(self, thisMethod, args));
            return (T) proxy;
        } catch (Exception e) {
            log.error("javassist proxy throws exception:{}", e);
        }
        return null;
    }
}
